package com.bauer.base.jvm.gc;

/**
 * @Author ：rui.wei
 * @Date ：Created in 11:14 2019/6/5
 * @Description：
 */
public class FinalizeEscapeGC {

    public static FinalizeEscapeGC SAVE_HOOK = null;


    /**
     * finalize 同一个对象的方法只能执行一次   实际应用避免使用该关键词
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();

        SAVE_HOOK = null;
        System.gc();
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            isAlive();
        } else {
            System.out.println("i am dead");
        }

        SAVE_HOOK = null;
        System.gc();
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            isAlive();
        } else {
            System.out.println("i am dead");
        }


    }

    public static void isAlive() {
        System.out.println("i am alive");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("execute finalize");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

}
